//向应用转账
$(function () {
    //清空信息
    $("input[name='devId']").val("");
    $("[name='money']").val("");
    $("[name='payPsw']").val("");
    $("#note").val("");
    $("#searchAPP").val("");
    loading();
    //var appName=getQueryString("appId");
    var user = getUser_C();
    ajaxGetPayPswStatus(getPayPswStatus);
    $('#searchAPP').click(function () {
        //$("#searchAPP").animate({width:"330px"},"slow","swing");
        $(this).css({border:"1px solid #ccc",background:"#fff url(/Lvscore_User_M/userWeb/static/images/searchIcon.png) no-repeat 3px 0px"});
        //解绑防止发送多次请求
        $(this).unbind('input propertychange');
        //结果展示，调用方法
        $(this).bind('input propertychange', function () {
            var condition = $('#searchAPP').val();
            if (isNotEmpty(condition)) {
                $(".friendList").show();
                $('#friend').empty();
                ajaxSearchAppByCondition(condition);
            } else {
                $(".friendList").hide();
            }
        })
        $(this).blur(function(){
            $("#searchAPP").css({border:"none",background:"#ebeff5 url(/Lvscore_User_M/userWeb/static/images/searchIcon.png) no-repeat 3px 0px"});
        });
        });
    $(".btnSure").click(function () {
        var money = $("[name='money']").val();
        if ($("[name='devId']").val() == "" || $("[name='devId']").val() == null) {
            alertBox("请填写一个应用", '');
        } else if (money == "" || money == null) {
            alertBox("请输入金额", '');
        } else if (!isMoney(money)) {
            alertBox("您输入的金额格式错误", '');
        } else if ($("[name='payPsw']").val() == "" || $("[name='payPsw']").val() == null) {
            alertBox("请输入支付密码", '');
        } else if (($("#balance").text() - money) < 0) {
            $(".blance").show();
        }else {
            /**
             * 验证输入的支付密码是否正确
             */
            ajaxValidateOldPayPsw($("[name='payPsw']").val(), ajaxTransferToAppExecute);
        }
    });
});

/**
 * 搜索应用
 * @param condition
 */
function ajaxSearchAppByCondition(condition) {
    var url = '/Lvscore_User_M/adScore/ajaxSearchAppByCondition';
    $.ajax({
        url: url,
        type: 'POST',
        data: {'condition': condition},
        success: function (data) {
            if (isNotEmpty(data) && data.length > 0) {
                $.each(data, function(i,e) {
                    $('#friend').append(
                        //循环体
                        "<li>" +
                        "<a href='javascript:void(0);' onclick='chooseDid("+ e.id+")'>" +//
                        "<input type='radio' name='friendList' ename='"+ e.name+"' id='e_" + e.id + "' onclick='return false'/> &nbsp;" +
                        "<label for='e_" + e.id + "' onclick='return false' style='line-height:25px;cursor: pointer;width:auto;'><span><img src='" + getImageUrl(e.logourl) + "'></span>" +
                        "<span title='" + e.name + "' style='display:inline-block;width:165px;text-align: left;margin-left: 15px;font-size:16px;'>" + getName(e.name) + "(cp" +e.id+ ")" +"</span></label>" +
                        "</a>" +
                        "</li>"
                    );
                });
            }else{
                //没有数据时
                $('#friend').append(
                   "<li style='height:30px;line-height:30px;font-size:18px;text-align: center;'>未查询到结果</li>"
                )
            }
        },
        error: function () {

        },
        dataType: 'json'
    });
}

function getImageUrl(url) {
    if (url == '' || url == null) {
        return "/Lvscore_User_M/userWeb/static/images/manageWrap_pic.png";
    } else {
        return url;
    }
}
function chooseDid(id) {
    var name = $('#e_' + id).attr("ename");
    $(".friendList").hide();
    $("#searchAPP").val("");
    $("#searchAPP").css({border:"none",background:"#ebeff5 url(/Lvscore_User_M/userWeb/static/images/searchIcon.png) no-repeat 3px 0px"});
    //$("#searchAPP").animate({width:"150px"},"slow","swing");
    $("[name='devId']").val(name);
    $("[name='money']").val("");
    $("[name='appID']").val(id);
    var user = getUser_C();
    if (user&&isNotEmpty($("[name='devId']").val())) {
        $(".balance").show();
        $("#balance").text(user.balance);
    }
}

function getName(name) {
    if (getLength(name) > 8) {
        return name.substring(0, 4) + "...";
    }
    return name;
}
/**
 * 加载用户可用的专项积分，用于验证输入金额是否大于可用金额
 */
//function ajaxtransferToDeveloper() {
//    var url = "/Lvscore_User_M/adScore/ajaxtransferToDeveloper";
//    $.post(
//        url,
//        function (data) {
//            $("#balance").text(data);
//        },
//        "json"
//    );
//}

/**
 * 验证用户专项积分是否足够支付的方法
 */
//function validateIfEnoughToPay() {
//    var balance = $("#balance").text();
//    var money = $("[name='money']").val();
//    (balance - money) < 0 ? $(".blance").show(): '';
//}
/**
 * 获取用户是否已经设置支付密码
 *      并根据返回值执行相应的函数
 */
function ajaxGetPayPswStatus(fn) {
    var url = "/Lvscore_User_M/account/ajaxGetPayPswStatus";
    $.post(
        url,
        function (data) {
            fn(data);
        },
        "json"
    );
}
//是否设置过密码
function getPayPswStatus(status) {
    if (status) {
        $(".loadingBox").hide();
        $("#paymentStatus").html('<a href="javascript:void(0)" onclick="forgotPayPsw()" class="lightgreen" style="font-size:16px;margin-left:5px;">&nbsp;忘记支付密码？</a>');

    } else {
        $(".loadingBox").hide();
        $("#paymentStatus").html('<a href="javascript:void(0)" class="lightgreen" style="font-size:16px;margin-left:5px;">&nbsp;设置支付密码？</a>');
        $(".confirmBox").show();
        $(".mask").show();
    }
}
/**
 * 支付密码正确后 确认向 应用 支付  执行
 * @param appId         应用id
 * @param outBalance    支付金额
 * @param note          转账备注（可没有）
 */
function ajaxTransferToAppExecute() {
    var appId = $("[name='appID']").val();
    var outBalance = $("[name='money']").val();
    var note = $("#note").val();
    var url = "/Lvscore_User_M/adScore/ajaxTransferToAppExecute";
    $.post(
        url,
        {
            'appId': appId,
            'outBalance': outBalance,
            'note': note
        },
        function (data) {
            if (data == 1) {
                var href = '/Lvscore_User_M/userWeb/views/ADadmin/payment/buyAPP_success.html';
                flushUser(href);
            } else if (data == -1) {
                alertBox('支付失败，请重试', '');
            } else {
                alertBox('服务器异常，请重试', '');
            }
        },
        "json"
    );
}